package com.h3c.nem.controller;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.eos.common.constant.StatusCodeEnum;
import com.eos.common.custom.BusinessException;
import com.eos.common.util.Result;
import com.github.pagehelper.PageInfo;
import com.h3c.nem.annotation.CheckRole;
import com.h3c.nem.cache.TbOfferWorkerCache;
import com.h3c.nem.dto.*;
import com.h3c.nem.dto.beisen.OcrDTO;
import com.h3c.nem.dto.sap.SubmitFormalWorkerIdDTO;
import com.h3c.nem.entity.TbApprovalRecord;
import com.h3c.nem.entity.TbOfferWorker;
import com.h3c.nem.entity.TbPersonnelRegisterMiddle;
import com.h3c.nem.enums.OfferWorkerStatusEnum;
import com.h3c.nem.enums.RoleType;
import com.h3c.nem.service.CommService;
import com.h3c.nem.service.ITbApprovalRecordService;
import com.h3c.nem.service.ITbOfferWorkerService;
import com.h3c.nem.service.ITbPersonnelRegisterMiddleService;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.BusiEnumDefine;
import com.h3c.nem.utils.CommonUtil;
import com.h3c.nem.vo.InsuredCityVO;
import com.h3c.nem.vo.TbOfferWorkerVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 预备员工基本信息控制层
 *
 * @author chenyifan
 * @since 2022-06-02 14:19:47
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tbOfferWorker")
public class TbOfferWorkerController {
    /**
     * 服务对象
     */
    private final ITbOfferWorkerService tbOfferWorkerService;

    private final CommService commService;

    private final ITbPersonnelRegisterMiddleService iPersonnelRegisterMiddleService;

    private final ITbApprovalRecordService iTbApprovalRecordService;

    /**
     * 保存基础信息
     *
     * @return
     */
    @PostMapping("/saveBasicInfo")
    public Result<String> saveBasicInfo(@RequestBody TbOfferWorkerDTO workerDTO) {
        try {
            tbOfferWorkerService.saveBasicInfo(workerDTO);
            return new Result(true, StatusCodeEnum.NORMAL);
        } catch (Exception e) {
            return new Result(false, StatusCodeEnum.ADD_FAIl);
        }
    }

    /**
     * 发起电子签署
     *
     * @return
     */
    @PostMapping("/startElectronicSignature")
    public Result<String> startElectronicSignature(@RequestBody List<String> workerIds) {
        try {
            return new Result(true, StatusCodeEnum.NORMAL, tbOfferWorkerService.startElectronicSignature(workerIds));
        } catch (Exception e) {
            log.error("发起电子签章失败,原因:{}", e.getMessage());
            return new Result(false, StatusCodeEnum.UNKNOW_ERROR.getCode(), e.getMessage());
        }
    }

    /**
     * 重新发起电子签署
     *
     * @return
     */
    @PostMapping("/reSignFile")
    public Result<String> reSignFile(@RequestBody List<ReSignDTO> reSignDTOS,
                                     @RequestParam String appId,
                                     @RequestParam Integer sceneType) {
        try {
            return new Result(true, StatusCodeEnum.NORMAL, tbOfferWorkerService.reSignFile(reSignDTOS, appId, sceneType));
        } catch (Exception e) {
            log.error("发起电子签章失败,原因:{}", e.getMessage());
            return new Result(false, StatusCodeEnum.UNKNOW_ERROR);
        }
    }

    /**
     * 生成正式工号
     *
     * @param submitFormalWorkerIdDTO
     * @return
     */
    @PostMapping("/submitOfGenFormalWorkerId")
    public Result<String> submitOfGenFormalWorkerId(@RequestBody SubmitFormalWorkerIdDTO submitFormalWorkerIdDTO) {
        try {
            String res = tbOfferWorkerService.submitOfGenFormalWorkerId(submitFormalWorkerIdDTO);
            return new Result<>(true, StatusCodeEnum.NORMAL, res);
        } catch (Exception e) {
            log.error("生成正式工号失败,原因:{}", e);
            return new Result<>(false, StatusCodeEnum.UNKNOW_ERROR.getCode(), e.getMessage());
        }
    }

    @PostMapping("/batchSubmitOfGenFormalWorkerId")
    public Result<String> batchSubmitOfGenFormalWorkerId(@RequestBody SubmitFormalWorkerIdDTO submitFormalWorkerIdDTO) {
        try {
            String res = tbOfferWorkerService.batchSubmitOfGenFormalWorkerId(submitFormalWorkerIdDTO);
            return new Result<>(true, StatusCodeEnum.NORMAL, res);
        } catch (Exception e) {
            log.error("生成正式工号失败,原因:{}", e.getMessage());
            return new Result<>(false, StatusCodeEnum.UNKNOW_ERROR);
        }
    }

    @GetMapping("/checkRdDeptType")
    public JSONObject checkRdDeptType(@RequestParam("deptNameChain") String deptNameChain) {
        JSONObject jsonObject = tbOfferWorkerService.checkRdDeptTypeAndManager(deptNameChain);
        return jsonObject;
    }


    /**
     * 回显基本信息
     *
     * @return
     */
    @GetMapping("/showBasicInfo")
    public Result<String> showBasicInfo() {
        try {
            TbOfferWorkerVO tbOfferWorkerVO = tbOfferWorkerService.showBasicInfo();
            return new Result(true, StatusCodeEnum.NORMAL, tbOfferWorkerVO);
        } catch (Exception e) {
            return new Result(false, StatusCodeEnum.SEARCH_FAIl);
        }
    }

    /**
     * 修改入职日期
     *
     * @return
     */
    @PostMapping("/updateEntryDate")
    public Result<String> updateEntryDate(@RequestBody UpdateEntryDateDTO updateEntryDateDTO) {
        try {
            tbOfferWorkerService.updateEntryDate(CommonUtil.getActivUser().getUserId(), updateEntryDateDTO);
            return new Result(true, StatusCodeEnum.NORMAL);
        } catch (Exception e) {
            return new Result(false, StatusCodeEnum.UNKNOW_ERROR.getCode(),e.getMessage());

        }
    }

    /**
     * 人工确认电子签署完成
     *
     * @return
     */
    @PostMapping("/confirmEsign")
    public Result<String> confirmEsign(@RequestBody List<String> workerIds) {
        try {
            for (String workerId : workerIds) {
                tbOfferWorkerService.confirmEsign(workerId);
            }
            return new Result(true, StatusCodeEnum.NORMAL);
        } catch (Exception e) {
            return new Result(false, StatusCodeEnum.UNKNOW_ERROR);

        }
    }

    /**
     * 线下签署
     *
     * @param workerIds 员工工号列表
     * @return
     */
    @PostMapping("/offlineSign")
    public Result<String> offlineSign(@RequestBody List<String> workerIds) {
        for (String workerId : workerIds) {
            TbOfferWorker offerWorker = tbOfferWorkerService.getById(workerId);
            if (StringUtils.isBlank(offerWorker.getContractType()) ||
                    Objects.isNull(offerWorker.getContractBeginDate()) ||
                    Objects.isNull(offerWorker.getContractEndDate()) ||
                    Objects.isNull(offerWorker.getProbationMonth())) {
                throw new AppBusinessException("请先完善工号为:"+offerWorker.getWorkerId()+"的合同相关信息");
            }
            tbOfferWorkerService.update(null, new LambdaUpdateWrapper<TbOfferWorker>()
                    .set(TbOfferWorker::getWorkerStatus, OfferWorkerStatusEnum.签署完成)
                    .set(TbOfferWorker::getOfflineOperator, commService.getLoginUserNameAndId())
                    .set(TbOfferWorker::getOfflineTime, new Date())
                    .eq(TbOfferWorker::getWorkerId, workerId)
            );
        }
        return new Result(true, StatusCodeEnum.NORMAL);
    }

    /**
     * 根据ocr识别的身份证上的信息更新
     *
     * @return
     */
    @PostMapping("/updateUserInfoByOCR")
    public Result<String> updateUserInfoByOCR(@RequestBody OcrDTO ocrDTO) {
        try {
            tbOfferWorkerService.updateUserInfoByOCR(ocrDTO);
            return new Result(true, StatusCodeEnum.NORMAL);
        } catch (Exception e) {
            log.error("根据ocr识别的身份证上的信息更新失败:{}", e.getMessage());
            return new Result(false, StatusCodeEnum.UNKNOW_ERROR);
        }
    }

    /**
     * 登录成功后确认一些文件
     *
     * @return
     */
    @GetMapping("/confirmFile")
    public Result<String> confirmFile() {
        try {
            tbOfferWorkerService.confirmFile();
            return new Result(true, StatusCodeEnum.NORMAL);
        } catch (BusinessException e) {
            return new Result(false, 400, e.getMessage());
        }
    }

    /**
     * 录入信息完成提交接口
     *
     * @return
     */
    @GetMapping("/finishFill")
    public Result<String> finishFill() {
        try {
            return new Result(true, StatusCodeEnum.NORMAL.getCode(), tbOfferWorkerService.finishFill());
        } catch (BusinessException e) {
            return new Result(false, 400, e.getMessage());
        }
    }

    /**
     * 邮件拒绝offer接口
     *
     * @return
     */
    @GetMapping("/refuseOffer")
    public Result<String> refuseOffer(@RequestParam String workerId, HttpServletResponse response) {
        try {
            tbOfferWorkerService.refuseOffer(workerId, response);
            return new Result(true, StatusCodeEnum.NORMAL);
        } catch (Exception e) {
            return new Result(false, 400, e.getMessage());
        }
    }

    /**
     * 邮件接受offer接口
     *
     * @return
     */
    @GetMapping("/acceptOffer")
    public Result<String> acceptOffer(@RequestParam String workerId, HttpServletResponse response) {
        try {
            tbOfferWorkerService.acceptOffer(workerId, response);
            return new Result(true, StatusCodeEnum.NORMAL);
        } catch (Exception e) {
            return new Result(false, 400, e.getMessage());
        }
    }

    /**
     * 审核计划入职时间
     *
     * @return
     */
    @PostMapping("/approvalPlanReportDate")
    public Result<String> approvalPlanReportDate(@RequestBody OfferWorkerEditDTO dto) {
        try {
            tbOfferWorkerService.approvalPlanReportDate(dto);
            return new Result<>(true, StatusCodeEnum.NORMAL);
        } catch (BusinessException e) {
            return new Result<>(false, 400, e.getMessage());
        }
    }

    /**
     * 获取填充情况
     *
     * @return
     */
    @GetMapping("/getFillStatus")
    public Result<String> getFillStatus() {
        try {
            return new Result(true, StatusCodeEnum.NORMAL, TbOfferWorkerCache.getFillStatus(CommonUtil.getActivUser().getUserId()));
        } catch (Exception e) {
            return new Result(false, 400, e.getMessage());
        }
    }

    /**
     * bp查询预入职员工
     *
     * @param dto offerWorker
     * @return
     */
    @GetMapping("/getOfferWorkerBp")
    public Result<PageInfo<TbOfferWorkerDTO>> getOfferWorkerBp(@ModelAttribute TbOfferWorkerDTO dto,
                                                               @RequestParam(value = "startDate", required = false) String startDate,
                                                               @RequestParam(value = "endDate", required = false) String endDate,
                                                               @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                               @RequestParam("isBp") Boolean isBp) {
        PageInfo<TbOfferWorkerDTO> res = tbOfferWorkerService.getOfferWorkerBp(dto, startDate, endDate, isBp, currentPage, pageSize);
        return new Result<>(true, StatusCodeEnum.NORMAL, res);
    }

    //编辑待入职员工
    @PostMapping("editPendingEmployees")
    public Result<String> editPendingEmployees(@RequestBody OfferWorkerEditDTO dto) {
        String res = tbOfferWorkerService.editPendingEmployees(dto);
        return new Result<>(true, StatusCodeEnum.NORMAL, res);
    }

    @PostMapping("editOfferWorker")
    public Result<String> editOfferWorker(@RequestBody OfferWorkerEditDTO dto) {
        String res = tbOfferWorkerService.editOfferWorker(dto);
        return new Result<>(true, StatusCodeEnum.NORMAL, res);
    }

    @PostMapping("/sscUpdateReportDate")
    public Result<String> sscUpdateReportDate(@RequestBody OfferWorkerEditDTO dto) {
        tbOfferWorkerService.sscUpdatePlanReportDate(dto);
        return new Result<>(true, StatusCodeEnum.NORMAL);
    }

    @GetMapping("searchWorker/{keyword}")
    public Result<List<TbOfferWorker>> searchWorker(@PathVariable String keyword) {
        List<TbOfferWorker> list = tbOfferWorkerService.searchWorker(keyword);
        return new Result<>(true, StatusCodeEnum.NORMAL, list);
    }

    @GetMapping("/getWorkerStatusCount")
    public Result<List<JSONObject>> getWorkerStatusCount(@RequestParam("isBp") Boolean isBp) {
        List<JSONObject> res = tbOfferWorkerService.getWorkerStatusCount(isBp);
        return new Result<>(true, StatusCodeEnum.NORMAL, res);
    }

    @GetMapping("/getWorkerDetail")
    public Result<Map<String, Object>> getWorkerDetail(@RequestParam("workerId") String workerId) {
        Map<String, Object> res = tbOfferWorkerService.getWorkerDetail(workerId);
        return new Result<>(true, StatusCodeEnum.NORMAL, res);
    }

    @PostMapping("/submitOfferAdjust")
    public Result<String> submitOfferAdjust(@RequestBody OfferAdjustDTO dto) {
        String res = tbOfferWorkerService.submitOfferAdjust(dto);
        return new Result<>(true, StatusCodeEnum.NORMAL, res);
    }

    @PostMapping("/sendHelpMsgWhenSubmit")
    public Result sendHelpMsgWhenSubmit(@RequestBody JSONObject obj) {
        String content = obj.getString("content");
        String type = obj.getString("type");
        if (!StringUtils.isEmpty(content.trim())) {
            tbOfferWorkerService.sendHelpMsgWhenSubmit(content, type);
        }
        return new Result(true, StatusCodeEnum.NORMAL);
    }

    @CheckRole(roleArray = {RoleType.ROLE_ADMIN, RoleType.USER_ROLE_OFFER_SSC_MANAGER, RoleType.USER_ROLE_OFFER_DEPT_MANAGER})
    @PostMapping("/updateEditBeisenAuth")
    public Result updateEditBeisenAuth(@RequestBody JSONObject object) {
        String workerId = object.getString("workerId");
        String auth = object.getString("auth");
        tbOfferWorkerService.updateEditBeisenAuth(workerId, auth);
        return new Result(true, StatusCodeEnum.NORMAL);
    }

    @GetMapping("/getOfferAdjust")
    public Result<JSONObject> getOfferAdjust(@RequestParam("workerId") String workerId, @RequestParam("recordId") String recordId) {
        JSONObject res = tbOfferWorkerService.getOfferAdjust(workerId, recordId);
        return new Result<>(true, StatusCodeEnum.NORMAL, res);
    }

    @PostMapping("/approvalOfferWorkerData")
    public Result<String> approvalOfferWorkerData(@RequestBody ApprovalDTO dto) {
        String res = tbOfferWorkerService.approvalOfferWorkerData(dto.getWorkerId(), dto.getApprovalNote(), dto.getApprovalType(), "", BusiEnumDefine.NOTICE_MAIL_SEND_YES);
        return new Result<>(true, StatusCodeEnum.NORMAL, res);
    }

    @PostMapping("/batchApprovalOfferWorkerData")
    public Result<String> batchApprovalOfferWorkerData(@RequestBody ApprovalDTO dto) {
        String res = tbOfferWorkerService.batchApprovalOfferWorkerData(dto.getWorkerId(), dto.getApprovalNote(),
                dto.getApprovalType(), "");
        if (res.equals("SUCCESS")) {
            return new Result<>(true, StatusCodeEnum.NORMAL, res);
        } else {
            return new Result<>(true, StatusCodeEnum.UNKNOW_ERROR.getCode(), res);
        }
    }

    //导入待入职员工信息
    @PostMapping("importPendingEmployees")
    public Result<String> importPendingEmployees(MultipartFile file) {
        Result<String> result = new Result<>(true, StatusCodeEnum.NORMAL, "SUCCESS");
        String excelJsonString = commService.parseExcelByTemplate("PENDING_EMPLOYEE_IMPORT", file);
        List<OfferWorkerEditDTO> workerEditDTOList = JSONArray.parseArray(excelJsonString, OfferWorkerEditDTO.class);
        workerEditDTOList = tbOfferWorkerService.lessCodeEditInformation(workerEditDTOList, result);
        StringBuilder errorInfo = new StringBuilder();
        workerEditDTOList.forEach(dto -> {
            try {
                tbOfferWorkerService.editPendingEmployees(dto);
            } catch (Exception e) {
                errorInfo.append(dto.getWorkerId()).append(" ");
            }
        });
        if (errorInfo.length() > 0) {
            String errorMessage = "\n以下预备员工[" + errorInfo + "]执行错误：";
            result.setCode(StatusCodeEnum.UNKNOW_ERROR.getCode());
            result.setMessage(result.getMessage() + errorMessage);
        }
        return result;
    }

    @PostMapping("importOfferWorker")
    public Result<String> importOfferWorker(MultipartFile file) {
        Result<String> result = new Result<>(true, StatusCodeEnum.NORMAL, "SUCCESS");
        String excelJsonString = commService.parseExcelByTemplate("OFFER_WORKER_IMPORT", file);
        List<OfferWorkerEditDTO> workerEditDTOList = JSONArray.parseArray(excelJsonString, OfferWorkerEditDTO.class);
        workerEditDTOList = tbOfferWorkerService.lessCodeEditInformation(workerEditDTOList, result);
        StringBuilder errorInfo = new StringBuilder();
        workerEditDTOList.forEach(dto -> {
            try {
                tbOfferWorkerService.editOfferWorker(dto);
            } catch (Exception e) {
                errorInfo.append(dto.getWorkerId()).append(" ");
            }
        });
        if (errorInfo.length() > 0) {
            String errorMessage = "\n以下预备员工[" + errorInfo + "]执行错误：";
            result.setCode(StatusCodeEnum.UNKNOW_ERROR.getCode());
            result.setMessage(result.getMessage() + errorMessage);
        }
        return result;
    }

    /**
     * 导出参保地
     */
    @PostMapping("exportInsuredCity")
    public Result<String> exportInsuredCity(@ModelAttribute TbOfferWorkerDTO dto,
                                            @RequestParam(value = "startDate", required = false) String startDate,
                                            @RequestParam(value = "endDate", required = false) String endDate,
                                            HttpServletResponse response) {
        try {
            long start = System.currentTimeMillis();
            log.info("参保地导出");
            List<TbOfferWorkerDTO> res = tbOfferWorkerService.getOfferWorkerBp(dto, startDate, endDate, false);
            List<InsuredCityVO> insuredCityVOList = JSONArray.parseArray(JSON.toJSONString(res), InsuredCityVO.class);
            //填表日期 和 注册地
            List<String> personnelRangeList = insuredCityVOList.stream().map(InsuredCityVO::getPersonnelRange).distinct().collect(Collectors.toList());
            if (!personnelRangeList.isEmpty()) {
                List<TbPersonnelRegisterMiddle> list = iPersonnelRegisterMiddleService.list(new LambdaQueryWrapper<TbPersonnelRegisterMiddle>()
                        .in(TbPersonnelRegisterMiddle::getPersonnelScope, personnelRangeList));
                Map<String, TbPersonnelRegisterMiddle> registerMiddleMap = list.stream().collect(Collectors.toMap(TbPersonnelRegisterMiddle::getPersonnelCode, o -> o));
                for (InsuredCityVO insuredCityVO : insuredCityVOList) {
                    TbPersonnelRegisterMiddle tbPersonnelRegisterMiddle = registerMiddleMap.get(insuredCityVO.getPersonnelRangeCode());
                    if (tbPersonnelRegisterMiddle != null) {
                        insuredCityVO.setRegistration(tbPersonnelRegisterMiddle.getRegistration());
                    }
                }
            }
            log.info("参保地数据准备1耗时： " + (System.currentTimeMillis()- start)/1000);
            List<String> workerIdList = insuredCityVOList.stream().map(InsuredCityVO::getWorkerId).distinct().collect(Collectors.toList());
            if (!workerIdList.isEmpty()) {
                List<TbApprovalRecord> list = iTbApprovalRecordService.list(new LambdaQueryWrapper<TbApprovalRecord>()
                        .in(TbApprovalRecord::getFlowId, workerIdList)
                        .eq(TbApprovalRecord::getApprovalType, TbApprovalRecord.RESERVE_STAFF_SUBMIT));
                Map<String, Date> dateMap = list.stream().collect(Collectors.groupingBy(TbApprovalRecord::getFlowId,
                        Collectors.collectingAndThen(Collectors.toList(),
                                records -> records.stream().map(TbApprovalRecord::getApprovalTime)
                                        .filter(Objects::nonNull).max(Date::compareTo).orElse(null))));
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                for (InsuredCityVO insuredCityVO : insuredCityVOList) {
                    Date approvalDate = dateMap.get(insuredCityVO.getWorkerId());
                    if (approvalDate != null) {
                        insuredCityVO.setSubmitTableDate(dateFormat.format(approvalDate));
                    }
                }
            }

            log.info("参保地数据准备2耗时： " + (System.currentTimeMillis()- start)/1000);
            File file = commService.generateExportFile("参保地导出", "INSURED_CITY_EXPORT", (List) insuredCityVOList);
            byte[] buffer = new byte[(int) file.length()];
            FileInputStream inputStream = new FileInputStream(file);
            inputStream.read(buffer);
            inputStream.close();

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding(Charsets.UTF_8.name());
            String resultFilename = URLEncoder.encode(file.getName(), Charsets.UTF_8.name());
            response.setHeader("Content-disposition", "attachment;filename=" + resultFilename);
            response.setHeader("issuccess", "1");
            response.setHeader("Access-Control-Expose-Headers", "Content-disposition,issuccess");
            IoUtil.write(response.getOutputStream(), true, buffer);

            return new Result<>(true, StatusCodeEnum.NORMAL, "SUCCESS");
        } catch (Exception e) {
            log.error("导出error:" + e);
            e.printStackTrace();
            throw new AppBusinessException("导出出错");
        }
    }

    @PostMapping("/exportOfferWorker")
    public Result<String> exportOfferWorker(@ModelAttribute TbOfferWorkerDTO dto,
                                            @RequestParam(value = "startDate", required = false) String startDate,
                                            @RequestParam(value = "endDate", required = false) String endDate,
                                            @RequestParam("isBp") Boolean isBp,
                                            HttpServletResponse response) {
        try {
            List<TbOfferWorkerDTO> res = tbOfferWorkerService.getOfferWorkerBp(dto, startDate, endDate, isBp);
            String excelCode = isBp ? "OFFER_WORKER_EXPORT" : "PENDING_EMPLOYEE_EXPORT";
            if (isBp) {
                res.forEach(r -> {
                    String directManager = r.getDirectManager();
                    if (StringUtils.isNotBlank(directManager)) {
                        String[] manager = directManager.split("/");
                        r.setDirectManagerName(manager[0]);
                        r.setDirectManager(manager[1]);
                    }
                    String teacherInfo = r.getTeacherInfo();
                    if (StringUtils.isNotBlank(teacherInfo)) {
                        String[] teacher = teacherInfo.split("/");
                        r.setTeacherInfoName(teacher[0]);
                        r.setTeacherInfo(teacher[1]);
                    }
                    String projectWorkerFlag = r.getProjectWorkerFlag();
                    if (StringUtils.isNotBlank(projectWorkerFlag)) {
                        if ("1".equals(projectWorkerFlag)) {
                            r.setProjectWorkerFlagStr("是");
                        } else {
                            r.setProjectWorkerFlagStr("否");
                        }
                    }
                });
            }

            File file = commService.generateExportFile("预备员工信息导出", excelCode, (List) res);
            byte[] buffer = new byte[(int) file.length()];
            FileInputStream inputStream = new FileInputStream(file);
            inputStream.read(buffer);
            inputStream.close();

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding(Charsets.UTF_8.name());
            String resultFilename = URLEncoder.encode(file.getName(), Charsets.UTF_8.name());
            response.setHeader("Content-disposition", "attachment;filename=" + resultFilename);
            response.setHeader("issuccess", "1");
            response.setHeader("Access-Control-Expose-Headers", "Content-disposition,issuccess");
            IoUtil.write(response.getOutputStream(), true, buffer);
            return new Result<>(true, StatusCodeEnum.NORMAL, "SUCCESS");
        } catch (Exception e) {
            log.error("导出error:" + e);
            throw new AppBusinessException("导出出错");
        }
    }

    //邮催
    @PostMapping("/postalReminder")
    public Result<String> postalReminder(@RequestBody JSONObject request) {
        tbOfferWorkerService.postalReminder(request.getString("workerIds"));
        return new Result<>(true, StatusCodeEnum.NORMAL, "SUCCESS");
    }

}

